package fr.mathis.ouestcharlie;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ToolsBDD {

	public static ToolsBDD instance;
	private SQLiteDatabase bdd;
	private MyDBOpenHelper database;
	
	public ToolsBDD(Context context)
	{
		database = new MyDBOpenHelper(context, "ouestcharlie.db", null, 6);
		open();
	}
	
	public static ToolsBDD getInstance(Context context)
	{
		if(instance == null)
			instance = new ToolsBDD(context);
		instance.insertPartie(0+"");
		
		return instance;		
	}
	
	public void open()
	{
		bdd = database.getWritableDatabase();
	}
 
	public void close()
	{
		bdd.close();
	}
	
	public SQLiteDatabase getBDD()
	{
		return bdd;
	}
	
	public boolean checkPartie(String input){
		Cursor c = bdd.query("partie", new String[] {"id"}, null, null, null, null, null);
		if (c.getCount() == 0)
			return false;
		else 
		{
			c.moveToFirst();
			while(!c.isAfterLast())
			{
				if(c.getInt(0)==Integer.parseInt(input))
				{
					return true;
				}
				c.moveToNext();
			}
		}
		return false;
	}
	
	public void insertPartie(String input)
	{
		bdd.execSQL("INSERT OR REPLACE INTO partie VALUES ("+input+")");
	}

	public int getLastGame(Context context) {
		int res = 0;
		
		for(int i = 0; i < ToolsPartie.NB_GAMES;i++)
		{
			if(ToolsBDD.getInstance(context).checkPartie(i+""))
			{
				res = i;
			}
		}
		return res;
	}
}
